import { camera, scene, renderer } from './utils/init'
import * as THREE from 'three'
import gsap from 'gsap'
let mesh,helper
function initBase() {
  const geometry = new THREE.PlaneGeometry(10, 10)
  const meterial = new THREE.MeshStandardMaterial({color: 0xffffff})
  const plane = new THREE.Mesh(geometry, meterial)
  plane.rotation.set(-Math.PI / 2, 0, 0)
  plane.receiveShadow = true
  scene.add(plane)
}


function createLight () {
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1)
  directionalLight.position.set(3, 3, 3)
  scene.add(directionalLight)
  directionalLight.castShadow = true
  // 光线跟着物体表面走 注意是设置mesh 而不是球体
  directionalLight.target = mesh
  helper = new THREE.DirectionalLightHelper(directionalLight, 1)
  scene.add(helper)
}

function createSphere (){
  const sphere = new THREE.SphereGeometry(1, 32, 16)
  const material = new THREE.MeshStandardMaterial( { color: 0x00ff00 } )
  mesh = new THREE.Mesh(sphere, material)
  mesh.position.set(0, 1, 0)
  mesh.castShadow = true
  scene.add(mesh)
}
camera.position.set(5, 5, 5)

function initAnimation () {
  let moveObj = gsap.to(mesh.position, {
    x: 5,
    duration: 1, 
    delay: 2, 
    repeat: -1, 
    yoyo: true, 
    ease: 'sine.out', 
    onStart () {
      console.log('开始了');
    },
    onUpdate () {
      console.log('更新了');
      // 在动画更新的时候更新辅助对象
      helper.update()
    },
    onComplete () {
      console.log('结束了');
    }
  })
  
  window.addEventListener('dblclick', () => {
    if (moveObj.isActive()) {
      moveObj.pause()
    } else {
      moveObj.resume()
    }
  })
}


// 渲染器接受阴影
renderer.shadowMap.enabled = true
initBase()
createSphere()
createLight()
initAnimation()